package com.rich.dmr.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.rich.dmr.DmrApplication;
import com.rich.dmr.R;
import com.rich.dmr.adapter.FrequencyGridAdapter;
import com.rich.dmr.ui.view.SimpleToolbar;
import com.rich.dmr.utils.SoundPoolUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import rich.dmr.DmrManager;

public class DigitalParamActivity extends BaseActivity implements View.OnClickListener,
        AdapterView.OnItemSelectedListener, FrequencyGridAdapter.OnItemClickListener {

    private String TAG = "rich---DigitalParamActivity";
    private DmrManager dmrManager;
    private SimpleToolbar simpleToolbar;
    private int whichActivity;
    private TextView tvContent;
    private EditText etContent;
    private LinearLayout ltSave;
    private Spinner spinner;
    private TypedArray typedArray;
    private FrequencyGridAdapter rxAdapter;
    private boolean isDisplay = false;
    private DmrHandler dmrHandler = new DmrHandler();

    private class DmrHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    etContent.setVisibility(View.GONE);
                    hideKeyboard(etContent);
                    tvContent.setVisibility(View.VISIBLE);
                    ltSave.setEnabled(false);
                    setTextViewContent(whichActivity);
                    if(isDisplay){
                        if(rxAdapter != null){
                            rxAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
                case 1:
                    setTextViewContent(whichActivity);
                    SoundPoolUtils.getInstance(DigitalParamActivity.this).playSound(false);
                    if(rxAdapter != null){
                        rxAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    @SuppressLint("WrongConstant")
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_digital_param);
        dmrManager = (DmrManager) getSystemService("dmrservice");

        whichActivity = getIntent().getIntExtra("whichActivity",
                R.string.digital_receiver_frequency);
        Log.d(TAG, "whichActivity=" + getString(whichActivity));
        isDisplay = getString(R.string.device_type).equals(Build.MODEL);
        findAllView(whichActivity);
        DmrApplication.getInstance().addActivity(this);
    }

    private void findAllView(int id) {
        simpleToolbar = findViewById(R.id.settings_tools_bar);
        LinearLayout ltEditText = findViewById(R.id.lt_edit_text);
        LinearLayout ltSpinner = findViewById(R.id.lt_spinner);
        LinearLayout ltGrid = findViewById(R.id.lt_grip);
        setToolsBar(id);
        switch (id) {
            case R.string.digital_call_type:
            case R.string.digital_volume:
            case R.string.digital_mic:
            case R.string.digital_power:
                //spinner
                ltSpinner.setVisibility(View.VISIBLE);
                ltEditText.setVisibility(View.GONE);
                ltGrid.setVisibility(View.GONE);
                spinner = findViewById(R.id.spinner_common);
                ArrayAdapter<String> adapter = new ArrayAdapter<>(
                        DigitalParamActivity.this,
                        android.R.layout.simple_list_item_1,
                        getArrayList(whichActivity));
                spinner.setAdapter(adapter);
                spinner.setOnItemSelectedListener(this);
                setSpinnerSelect(whichActivity);
                break;
            case R.string.digital_receiver_frequency:
            case R.string.digital_transmit_frequency:
                //text view
                ltEditText.setVisibility(View.VISIBLE);
                ltSpinner.setVisibility(View.GONE);
                tvContent = findViewById(R.id.tv_out_content);
                etContent = findViewById(R.id.et_in_content);
                ltSave = findViewById(R.id.lt_save_content);
                tvContent.setOnClickListener(this);
                ltSave.setOnClickListener(this);
                ltSave.setEnabled(false);
                setTextViewContent(whichActivity);
                //grid view
                if(isDisplay){
                    ltGrid.setVisibility(View.VISIBLE);
                    RecyclerView recyclerView = findViewById(R.id.frequency_list);
                    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,
                            StaggeredGridLayoutManager.VERTICAL));
                    rxAdapter = new FrequencyGridAdapter(DigitalParamActivity.this,
                            getArrayList(whichActivity), whichActivity);
                    recyclerView.setAdapter(rxAdapter);
                    rxAdapter.setOnClickListener(this);
                }
                break;
            case R.string.digital_local_id:
            case R.string.digital_group_list:
            case R.string.digital_transmit_contact:
                //text view
                ltEditText.setVisibility(View.VISIBLE);
                ltSpinner.setVisibility(View.GONE);
                tvContent = findViewById(R.id.tv_out_content);
                etContent = findViewById(R.id.et_in_content);
                ltSave = findViewById(R.id.lt_save_content);
                tvContent.setOnClickListener(this);
                ltSave.setOnClickListener(this);
                ltSave.setEnabled(false);
                setTextViewContent(whichActivity);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.txt_left_title:
                finish();
                break;
            case R.id.tv_out_content:
                tvContent.setVisibility(View.GONE);
                etContent.setVisibility(View.VISIBLE);
                ltSave.setEnabled(true);
                setInputType(whichActivity);
                break;
            case R.id.lt_save_content:
                String content = etContent.getText().toString();
                if (!content.equals("")) {
                    saveTextViewData(content);
                    dmrHandler.sendEmptyMessageDelayed(0, 80);
                }
                break;
            default:
                break;
        }
    }
    //adapter event
    @Override
    public void ItemClickListener(View view, int position) {
        switch (whichActivity) {
            case R.string.digital_receiver_frequency:
                dmrManager.setReceiveFrequency(Integer.valueOf(getArrayList(whichActivity).get(position)));
                dmrManager.flush();
                dmrHandler.sendEmptyMessageDelayed(1, 80);
                break;
            case R.string.digital_transmit_frequency:
                dmrManager.setTransmitFrequency(Integer.valueOf(getArrayList(whichActivity).get(position)));
                dmrManager.flush();
                dmrHandler.sendEmptyMessageDelayed(1, 80);
                break;
        }
    }
    //spinner select
    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
        saveSpinnerData(position);
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    @Override
    public void ItemLongClickListener(View view, int position) {

    }
    // save text
    public void saveTextViewData(String content) {
        if (dmrManager == null) {
            return;
        }
        Log.d(TAG, "saveTextViewData content=" + content);
        switch (whichActivity) {
            case R.string.digital_receiver_frequency:
                int mRxFreqVal = (int) (Double.valueOf(content.trim()) * 1000000);
                if (mRxFreqVal < 400000000 || mRxFreqVal > 480000000) {
                    Toast.makeText(this, "invalid", Toast.LENGTH_SHORT).show();
                    return;
                }

                if ((mRxFreqVal % 12500) != 0) {
                    Toast.makeText(this, "invalid", Toast.LENGTH_SHORT).show();
                    return;
                }

                dmrManager.setReceiveFrequency(mRxFreqVal);
                dmrManager.flush();
                break;
            case R.string.digital_transmit_frequency:
                int mTxFreqVal = (int) (Double.valueOf(content.trim()) * 1000000);
                if (mTxFreqVal < 400000000 || mTxFreqVal > 480000000) {
                    Toast.makeText(this, "invalid", Toast.LENGTH_SHORT).show();
                    return;
                }

                if ((mTxFreqVal % 12500) != 0) {
                    Toast.makeText(this, "invalid", Toast.LENGTH_SHORT).show();
                    return;
                }

                dmrManager.setTransmitFrequency(mTxFreqVal);
                dmrManager.flush();
                break;
            case R.string.digital_local_id:
                int mLocalIdVal = Integer.valueOf(content.trim());
                if (mLocalIdVal <= 0 || mLocalIdVal > 16776415) {
                    Toast.makeText(this, "invalid", Toast.LENGTH_SHORT).show();
                    return;
                }
                dmrManager.setLocalId(mLocalIdVal);
                dmrManager.flush();
                break;
            case R.string.digital_group_list:
                String mGroupListVal = content.trim();
                String originGroupList = dmrManager.getGroupList();
                String[] groupString = originGroupList.split("/");
                for (int i = 0; i <groupString.length; i++) {
                    if(mGroupListVal.equals(groupString[i])){
                        Toast.makeText(this, "group exist", Toast.LENGTH_SHORT).show();
                        return ;
                    }
                }

                if(Arrays.asList(dmrManager.getGroupList().split("/")).contains(String.valueOf(mGroupListVal))){
                    Toast.makeText(this, "group exist", Toast.LENGTH_SHORT).show();
                    return ;
                }

                if (groupString.length > 32) {
                    Toast.makeText(this, "over max group size", Toast.LENGTH_SHORT).show();
                    return;
                }

                int mGroupList = Integer.valueOf(content.trim());
                if (mGroupList <= 0 || (mGroupList > 16776415)) {
                    Toast.makeText(this, "group invalid", Toast.LENGTH_SHORT).show();
                    return;
                }
                dmrManager.setGroup(Integer.valueOf(mGroupListVal));
                dmrManager.flush();
                break;
            case R.string.digital_transmit_contact:
                int mTxContactVal = Integer.valueOf(content.trim());
                if (mTxContactVal <= 0 || (mTxContactVal > 16776415 && mTxContactVal < 16777200) || mTxContactVal > 16777215) {
                    Toast.makeText(this, "invalid", Toast.LENGTH_SHORT).show();
                    return;
                }
                dmrManager.setTransmitContact(mTxContactVal);
                dmrManager.flush();
                break;
            default:
                break;
        }
    }

    // save spinner
    public void saveSpinnerData(int content) {
        if (dmrManager == null) {
            return;
        }
        Log.d(TAG, "saveSpinnerData content=" + content);
        switch (whichActivity) {
            case R.string.digital_call_type:
                dmrManager.setContactType(content);
                dmrManager.flush();
                break;
            case R.string.digital_volume:
                dmrManager.setVolume(content + 1);
                dmrManager.flush();
                break;
            case R.string.digital_mic:
                dmrManager.setMicGain(content);
                dmrManager.flush();
                break;
            case R.string.digital_power:
                dmrManager.setPower(content);
                dmrManager.flush();
                break;
            default:
                break;
        }
    }

    //tool bar
    private void setToolsBar(int id) {
        simpleToolbar.setLeftTitleClickListener(this);
        simpleToolbar.setLeftTitleDrawable(R.mipmap.nav_back_icon);
        simpleToolbar.setMainTitle(getString(id));
    }

    //text view
    public void setTextViewContent(int id) {
        if (dmrManager == null) {
            return;
        }
        Log.d(TAG, "setText id=" + id);
        String content = null;
        switch (id) {
            case R.string.digital_receiver_frequency:
                content = String.valueOf(div(dmrManager.getReceiveFrequency(), 1000000));
                break;
            case R.string.digital_transmit_frequency:
                content = String.valueOf(div(dmrManager.getTransmitFrequency(), 1000000));
                break;
            case R.string.digital_local_id:
                content = String.valueOf(dmrManager.getLocalId());
                break;
            case R.string.digital_group_list:
                StringBuilder builder = new StringBuilder();
                String originGroupList = dmrManager.getGroupList();
                if(!originGroupList.equals("")){
                    String[] groupString = originGroupList.split("/");
                    int len = groupString.length;
                    for (int i = 0; i <len; i++) {
                        builder.append(groupString[len-i-1]);
                        builder.append("/");
                    }
                }
                content = builder.toString();
                break;
            case R.string.digital_transmit_contact:
                content = String.valueOf(dmrManager.getTransmitContact());
                break;
            default:
                break;
        }
        tvContent.setText(content);
    }

    //spinner
    public void setSpinnerSelect(int id) {
        if (dmrManager == null) {
            return;
        }
        Log.d(TAG, "setSpinnerSelect id=" + id);
        switch (id) {
            case R.string.digital_call_type:
                int callType = dmrManager.getContactType();
                spinner.setSelection(callType);
                break;
            case R.string.digital_volume:
                int volume = dmrManager.getVolume() - 1;
                spinner.setSelection(volume);
                break;
            case R.string.digital_mic:
                int mic = dmrManager.getMicGain();
                spinner.setSelection(mic);
                break;
            case R.string.digital_power:
                int power = dmrManager.getPower();
                spinner.setSelection(power);
                break;
            default:
                break;
        }
    }

    private List<String> getArrayList(int id) {
        List<String> dataList = new ArrayList<>();
        switch (id) {
            case R.string.digital_call_type:
                typedArray = getResources().obtainTypedArray(R.array.contact_type);
                break;
            case R.string.digital_volume:
                typedArray = getResources().obtainTypedArray(R.array.volume_type);
                break;
            case R.string.digital_mic:
                typedArray = getResources().obtainTypedArray(R.array.mic_type);
                break;
            case R.string.digital_power:
                typedArray = getResources().obtainTypedArray(R.array.power_type);
                break;
            case R.string.digital_receiver_frequency:
                typedArray = getResources().obtainTypedArray(R.array.rx_fre_type);
                break;
            case R.string.digital_transmit_frequency:
                typedArray = getResources().obtainTypedArray(R.array.tx_fre_type);
                break;
            default:
                break;
        }
        if (typedArray != null) {
            for (int i = 0; i < typedArray.length(); i++) {
                dataList.add(typedArray.getString(i));
            }
        }
        return dataList;
    }

    public void setInputType(int id) {
        switch (id) {
            case R.string.digital_local_id:
            case R.string.digital_transmit_contact:
                etContent.setInputType(InputType.TYPE_CLASS_NUMBER);
                break;
            case R.string.digital_group_list:
                etContent.setInputType(InputType.TYPE_CLASS_NUMBER);
                break;
            default:
                break;
        }
    }

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    public static BigDecimal div(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, 4, BigDecimal.ROUND_HALF_UP);
    }
}
